import Vue from 'vue'
import VueRouter from 'vue-router'
// 使用路由的懒加载，引入组件
const Login = () => import('@/pages/Login/index.vue')
const Layout = () => import('@/pages/Home/Layout.vue')
const Home = () => import('@/pages/Home/Home.vue')
const Content = () => import('@/pages/Home/Content.vue')
const ImgMaterial = () => import('@/pages/Home/imgMaterial.vue')
const Publish = () => import('@/pages/Home/Publish.vue')
const Comment = () => import('@/pages/Home/Comment.vue')
const Fans = () => import('@/pages/Home/Fans.vue')
const Setting = () => import('@/pages/Home/Setting.vue')
Vue.use(VueRouter)

const routes = [
  { path: '/login', name: 'login', component: Login },
  {
    path: '/',
    name: 'layout',
    component: Layout,
    children: [
      { path: '', name: 'home', component: Home },
      { path: '/content', name: 'content', component: Content },
      { path: '/imgMaterial', name: 'imgMaterial', component: ImgMaterial },
      { path: '/publish', name: 'publish', component: Publish },
      { path: '/comment', name: 'comment', component: Comment },
      { path: '/fans', name: 'fans', component: Fans },
      { path: '/setting', name: 'setting', component: Setting }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
// 这些都是需要被守卫的
const guard = ['/', '/content', '/imgMaterial', '/publish', '/comment', '/fans', '/setting']
router.beforeEach((to, from, next) => {
  // console.log(to)
  // console.log(from)

  // 如果要去的地址存在，还需要判断token是否存在，没有就回到登录页
  if (guard.includes(to.path)) {
    if (window.localStorage.getItem('myToken')) {
      next()
    } else {
      // 知道想去哪里，如果登录了直接跳转过去
      // next(`/login?name=${to.name}&redirect= ${to.path}`)
      next(`/login?redirect=${to.path}`)
    }
  } else {
    next()
  }
  // if (!guard.includes(to.path) || !window.localStorage.getItem('myToken')) {
  //   next(`/login?redirect=${to.path}`)
  // } else {
  //   next()
  // }
})

export default router
